<template>
    <van-sticky>
        <van-nav-bar :title="title" left-text="返回" left-arrow @click-left="onClickLeft">
            <template #right>
                <span @click="onClickRight" style="color: #1989fa">提交</span>
            </template>
        </van-nav-bar>
    </van-sticky>
    <div style="margin-top: 1rem">

        <van-field class="data-field" v-model="professionText" is-link readonly label="专业" placeholder="请选择专业"
            @click="handleProfessionClick" :disabled="professionLoading" />

        <van-field class="data-field" v-model="impactLevelText" is-link readonly label="影响程度" placeholder="请选择影响程度"
            @click="handleImpactClick" :disabled="optionsLoading" />

        <van-field class="data-field" v-model="areaTypeText" is-link readonly label="区域类型" placeholder="请选择区域类型"
            @click="handleAreaTypeCascadeClick" :disabled="optionsLoading" />

        <van-field class="data-field" v-model="locationText" is-link readonly label="位置" placeholder="请选择位置"
            @click="handleLocationClick" :disabled="locationLoading" />

        <van-field class="data-field" v-model="problemAttributeText" is-link readonly label="问题属性" placeholder="请选择问题属性"
            @click="handleProblemAttributeClick" :disabled="optionsLoading" />

        <van-field class="data-field" v-model="jointDebuggingText" is-link readonly label="联调项目" placeholder="请选择联调项目"
            @click="handleJointDebuggingClick" :disabled="optionsLoading" />

        <van-field class="data-field" v-model="securityText" is-link readonly label="责任单位" placeholder="请选择责任单位"
            @click="handleSecurityClick" :disabled="optionsLoading" />



        <van-popup v-model:show="showProfessionPicker" position="bottom">
            <van-search v-model="professionSearchKeyword" placeholder="搜索专业" @search="onProfessionSearch"
                @clear="clearProfessionSearch" />
            <van-cascader title="请选择专业" :options="professionFilteredOptions" v-model="professionSelected"
                @close="showProfessionPicker = false" @finish="onProfessionFinish" :closeable="false" />
        </van-popup>


        <van-popup v-model:show="showImpactPicker" position="bottom">
            <van-cascader title="请选择影响程度" :options="impactFilteredOptions" v-model="impactSelected"
                @close="showImpactPicker = false" @finish="onImpactFinish" :closeable="false" />
        </van-popup>


        <van-popup v-model:show="showAreaTypePicker" position="bottom">
            <van-cascader :title="areaTypeCascaderTitle" :options="areaTypeCascadeOptions" v-model="areaTypeSelected"
                @close="showAreaTypePicker = false" @finish="onAreaTypeFinish" @change="onAreaTypeChange"
                :closeable="false" />
        </van-popup>


        <van-popup v-model:show="showLocationPicker" position="bottom">
            <van-cascader title="请选择位置" :options="locationFilteredOptions" v-model="locationSelected"
                @close="showLocationPicker = false" @finish="onLocationFinish" :closeable="false" />
        </van-popup>


        <van-popup v-model:show="showProblemAttributePicker" position="bottom">
            <van-cascader title="请选择问题属性" :options="problemAttributeFilteredOptions" v-model="problemAttributeSelected"
                @close="showProblemAttributePicker = false" @finish="onProblemAttributeFinish" :closeable="false" />
        </van-popup>


        <van-popup v-model:show="showJointDebuggingPicker" position="bottom">
            <van-cascader title="请选择联调项目" :options="jointDebuggingFilteredOptions" v-model="jointDebuggingSelected"
                @close="showJointDebuggingPicker = false" @finish="onJointDebuggingFinish" :closeable="false" />
        </van-popup>


        <van-popup v-model:show="showSecurityPicker" position="bottom">
            <van-search v-model="securitySearchKeyword" placeholder="搜索责任单位" @search="onSecuritySearch"
                @clear="clearSecuritySearch" />
            <van-cascader title="请选择责任单位" :options="securityFilteredOptions" v-model="securitySelected"
                @close="showSecurityPicker = false" @finish="onSecurityFinish" :closeable="false" />
        </van-popup>

    </div>
</template>

<script setup>
import { onMounted, ref, computed } from "vue";
import { useRouter } from "vue-router";
import tbwtAPI from "@/api/tbwt.js";
import { extractAllOptionsToJson } from "@/utils/Misc";

const router = useRouter();
const title = ref("提报问题");


const showProfessionPicker = ref(false);
const professionText = ref("");
const professionSelected = ref("");
const professionCascadeOptions = ref([]);
const professionData = ref([]);
const professionLoading = ref(true);
const professionSearchKeyword = ref("");
const professionFilteredOptions = ref([]);


const showImpactPicker = ref(false);
const impactLevelText = ref("");
const impactSelected = ref("");
const impactOptions = ref([]);
const impactFilteredOptions = ref([]);


const locationText = ref("");
const locationSelected = ref("");
const locationOptions = ref([]);
const showLocationPicker = ref(false);
const locationFilteredOptions = ref([]);
const locationLoading = ref(true);



const problemAttributeText = ref("");
const problemAttributeSelected = ref("");
const problemAttributeOptions = ref([]);
const showProblemAttributePicker = ref(false);
const problemAttributeFilteredOptions = ref([]);


const jointDebuggingText = ref("");
const jointDebuggingSelected = ref("");
const jointDebuggingOptions = ref([]);
const showJointDebuggingPicker = ref(false);
const jointDebuggingFilteredOptions = ref([]);


const showAreaTypePicker = ref(false);
const areaTypeText = ref("");
const areaTypeSelected = ref("");
const areaTypeCascadeOptions = ref([]);
const areaTypeCascaderTitle = ref("请选择区域类型");


const showSecurityPicker = ref(false);
const securityText = ref("");
const securitySelected = ref("");
const securityCascadeOptions = ref([]);
const securityData = ref([]);
const securitySearchKeyword = ref("");
const securityFilteredOptions = ref([]);


const allOptionsData = ref({});
const optionsLoading = ref(true);


const onClickLeft = () => {
    router.back();
};

const onClickRight = () => {
    console.log("提交");
    console.log("选中的专业文本:", professionText.value);
    console.log("选中的专业值:", professionSelected.value);
    console.log("选中的影响程度文本:", impactLevelText.value);
    console.log("选中的影响程度值:", impactSelected.value);
    console.log("选中的位置文本:", locationText.value);
    console.log("选中的位置值:", locationSelected.value);
    console.log("选中的问题属性文本:", problemAttributeText.value);
    console.log("选中的问题属性值:", problemAttributeSelected.value);
    console.log("选中的联调项目文本:", jointDebuggingText.value);
    console.log("选中的联调项目值:", jointDebuggingSelected.value);
    console.log("选中的区域类型文本:", areaTypeText.value);
    console.log("选中的区域类型值:", areaTypeSelected.value);
    console.log("选中的责任单位文本:", securityText.value);
    console.log("选中的责任单位值:", securitySelected.value);
};



onMounted(async () => {
    optionsLoading.value = true;
    professionLoading.value = true;
    try {
        await Promise.all([getOptions(), getProfession(), getSecurity()]);
    } catch (error) {
        console.error("部分数据加载失败:", error);
    } finally {
        optionsLoading.value = false;
        professionLoading.value = false;
    }
});
const handleProfessionClick = () => {
    if (
        professionCascadeOptions.value.length === 0 &&
        professionData.value.length > 0
    ) {
        buildProfessionCascadeOptions();
    }

    professionFilteredOptions.value = [...professionCascadeOptions.value];
    professionSearchKeyword.value = "";
    showProfessionPicker.value = true;
};

const buildProfessionCascadeOptions = () => {
    const buildOptions = (nodes) => {
        if (!nodes || !Array.isArray(nodes)) return [];
        return nodes.map((node) => ({
            text: node.name || node.text || node.label || JSON.stringify(node),
            value: node.value || node.id || node.text,
            children:
                node.nodes && node.nodes.length > 0 ? buildOptions(node.nodes) : [],
        }));
    };
    professionCascadeOptions.value = buildOptions(professionData.value);
    professionFilteredOptions.value = [...professionCascadeOptions.value];
};

const onProfessionSearch = (keyword) => {

    professionSearchKeyword.value = keyword;
    if (!keyword.trim()) {

        professionFilteredOptions.value = [...professionCascadeOptions.value];
        return;
    }
    const filter = (options) =>
        options
            .map((option) => {
                const isMatch = option.text
                    .toLowerCase()
                    .includes(keyword.toLowerCase());

                const children = option.children || [];
                const filteredChildren =
                    children.length > 0 ? filter(children) : [];

                if (isMatch || filteredChildren.length > 0) {
                    return { ...option, children: filteredChildren };
                }
                return null;
            })
            .filter(Boolean);

    professionFilteredOptions.value = filter(professionCascadeOptions.value);
};

const clearProfessionSearch = () => {

    professionSearchKeyword.value = "";
    professionFilteredOptions.value = [...professionCascadeOptions.value];
};

const onProfessionChange = (value) => {
    console.log(value);
};

const onProfessionFinish = ({ selectedOptions }) => {
    if (!selectedOptions || selectedOptions.length === 0) {
        professionText.value = "";
        professionSelected.value = "";
    } else {
        professionText.value = selectedOptions.map((o) => o.text).join(" / ");
        professionSelected.value =
            selectedOptions[selectedOptions.length - 1]?.value || "";
    }
    showProfessionPicker.value = false;
};


const handleImpactClick = () => {
    if (impactOptions.value.length === 0 && allOptionsData.value["影响程度"]) {
        impactOptions.value = (allOptionsData.value["影响程度"] || []).map(
            (item) => ({
                text: item.label,
                value: item.value,
            })
        );
        impactFilteredOptions.value = [...impactOptions.value];
    }
    showImpactPicker.value = true;
};

const onImpactFinish = ({ selectedOptions }) => {
    if (!selectedOptions || selectedOptions.length === 0) {
        impactLevelText.value = "";
        impactSelected.value = "";
    } else {
        impactLevelText.value = selectedOptions[0]?.text || "";
        impactSelected.value = selectedOptions[0]?.value || "";
    }
    showImpactPicker.value = false;
};


const handleLocationClick = () => {
    locationFilteredOptions.value = [...locationOptions.value];
    showLocationPicker.value = true;
};

const onLocationFinish = ({ selectedOptions }) => {
    if (!selectedOptions || selectedOptions.length === 0) {
        locationText.value = "";
        locationSelected.value = "";
    } else {
        locationText.value = selectedOptions[0]?.text || "";
        locationSelected.value = selectedOptions[0]?.value || "";
    }
    showLocationPicker.value = false;
};


const handleProblemAttributeClick = () => {
    if (
        problemAttributeOptions.value.length === 0 &&
        allOptionsData.value["问题属性"]
    ) {
        problemAttributeOptions.value = (
            allOptionsData.value["问题属性"] || []
        ).map((item) => ({
            text: item.label,
            value: item.value,
        }));
        problemAttributeFilteredOptions.value = [...problemAttributeOptions.value];
    }
    showProblemAttributePicker.value = true;
};

const onProblemAttributeFinish = ({ selectedOptions }) => {
    if (!selectedOptions || selectedOptions.length === 0) {
        problemAttributeText.value = "";
        problemAttributeSelected.value = "";
    } else {
        problemAttributeText.value = selectedOptions[0]?.text || "";
        problemAttributeSelected.value = selectedOptions[0]?.value || "";
    }
    showProblemAttributePicker.value = false;
};


const handleJointDebuggingClick = () => {
    if (
        jointDebuggingOptions.value.length === 0 &&
        allOptionsData.value["联调项目"]
    ) {
        jointDebuggingOptions.value = (
            allOptionsData.value["联调项目"] || []
        ).map((item) => ({
            text: item.label,
            value: item.value,
        }));
        jointDebuggingFilteredOptions.value = [...jointDebuggingOptions.value];
    }
    showJointDebuggingPicker.value = true;
};

const onJointDebuggingFinish = ({ selectedOptions }) => {
    if (!selectedOptions || selectedOptions.length === 0) {
        jointDebuggingText.value = "";
        jointDebuggingSelected.value = "";
    } else {
        jointDebuggingText.value = selectedOptions[0]?.text || "";
        jointDebuggingSelected.value = selectedOptions[0]?.value || "";
    }
    showJointDebuggingPicker.value = false;
};


const handleAreaTypeCascadeClick = () => {
    showAreaTypePicker.value = true;
};

const onAreaTypeFinish = ({ selectedOptions }) => {
    if (!selectedOptions || selectedOptions.length === 0) {
        areaTypeText.value = "";
        areaTypeSelected.value = "";
    } else {
        const firstLevelValue = selectedOptions[0]?.value;
        if (firstLevelValue === "轨行区" && selectedOptions.length >= 4) {
            const direction = selectedOptions[1]?.text || "";
            const startStation = selectedOptions[2]?.text || "";
            const endStation = selectedOptions[3]?.text || "";
            areaTypeText.value = `${direction}方向 ${startStation}至${endStation}`;
            areaTypeSelected.value = `${direction}|${startStation}|${endStation}`;
        } else {
            areaTypeText.value = selectedOptions.map((o) => o.text).join(" / ");
            areaTypeSelected.value =
                selectedOptions[selectedOptions.length - 1]?.value || "";
        }
    }
    showAreaTypePicker.value = false;
};

const onAreaTypeChange = async ({ selectedOptions }) => {
    if (!selectedOptions || selectedOptions.length === 0) return;
    const firstLevelOption = selectedOptions[0];
    const firstLevelValue = firstLevelOption?.value;
    if (!firstLevelValue) return;
    const specialFirstLevelValues = ['控制中心', '中间风井'];
    if (specialFirstLevelValues.includes(firstLevelValue)) {
        areaTypeCascadeOptions.value = areaTypeCascadeOptions.value.map((opt) => {
            if (opt.value === firstLevelValue) {
                const { children, ...rest } = opt;
                return { ...rest };
            }
            return opt;
        });
        return;
    }

    if (selectedOptions.length === 1) {
        try {
            const childrenOptions = buildAreaTypeChildrenOptions(firstLevelValue);
            areaTypeCascadeOptions.value = areaTypeCascadeOptions.value.map((opt) => {
                if (opt.value === firstLevelValue) {
                    return { ...opt, children: childrenOptions };
                }
                return opt;
            });
            const res = await tbwtAPI.getLocation(firstLevelValue);
            locationOptions.value = res.data.position.map(item => ({
                value: item.id,
                text: item.name,
            }))
            locationLoading.value = false;
        } catch (error) {
            console.error("加载区域类型子项失败:", error);
        }
    }
};


const handleSecurityClick = () => {
    if (
        securityCascadeOptions.value.length === 0 &&
        securityData.value.length > 0
    ) {
        buildSecurityCascadeOptions();
    }

    securityFilteredOptions.value = [...securityCascadeOptions.value];
    securitySearchKeyword.value = "";
    showSecurityPicker.value = true;
};

const buildSecurityCascadeOptions = () => {
    const buildOptions = (nodes) => {
        if (!nodes || !Array.isArray(nodes)) return [];
        return nodes.map((node) => {
            const option = {
                text: node.name || node.text || node.label || JSON.stringify(node),
                value: node.value || node.id || node.text,
            };
            if (node.nodes && Array.isArray(node.nodes) && node.nodes.length > 0) {
                option.children = buildOptions(node.nodes);
            }
            return option;
        });
    };
    securityCascadeOptions.value = buildOptions(securityData.value);
    securityFilteredOptions.value = [...securityCascadeOptions.value];
};

const onSecuritySearch = (keyword) => {

    securitySearchKeyword.value = keyword;
    if (!keyword.trim()) {

        securityFilteredOptions.value = [...securityCascadeOptions.value];
        return;
    }
    const filter = (options) =>
        options
            .map((option) => {
                const isMatch = option.text
                    .toLowerCase()
                    .includes(keyword.toLowerCase());

                const children = option.children || [];
                const filteredChildren =
                    children.length > 0 ? filter(children) : [];

                if (isMatch || filteredChildren.length > 0) {
                    return { ...option, children: filteredChildren };
                }
                return null;
            })
            .filter(Boolean);

    securityFilteredOptions.value = filter(securityCascadeOptions.value);
};

const clearSecuritySearch = () => {

    securitySearchKeyword.value = "";
    securityFilteredOptions.value = [...securityCascadeOptions.value];
};

const onSecurityFinish = ({ selectedOptions }) => {
    if (!selectedOptions || selectedOptions.length === 0) {
        securityText.value = "";
        securitySelected.value = "";
    } else {
        securityText.value = selectedOptions.map((o) => o.text).join(" / ");
        securitySelected.value =
            selectedOptions[selectedOptions.length - 1]?.value || "";
    }
    showSecurityPicker.value = false;
};


const getOptions = async () => {
    try {
        const res = await tbwtAPI.getAddProblemForm();
        const options = extractAllOptionsToJson(res.data);
        allOptionsData.value = { ...options };
        if (options["开始站点(必填)"]) {
            allOptionsData.value.站点 = options["开始站点(必填)"];
            delete allOptionsData.value["开始站点(必填)"];
        }
        buildAreaTypeFirstLevelOptions();
    } catch (error) {
        console.error("获取选项数据失败:", error);
    }
};

const buildAreaTypeFirstLevelOptions = () => {
    const areaTypes = [
        "控制中心",
        "中间风井",
        "车站",
        "场段",
        "主变电所",
        "轨行区",
    ];
    areaTypeCascadeOptions.value = areaTypes.map((type) => {
        const option = {
            text: type,
            value: type,
        };
        if (type !== "控制中心" && type !== "中间风井") {
            option.children = [];
        }
        return option;
    });
};



const getProfession = async () => {
    try {
        const res = await tbwtAPI.getProfession();
        professionData.value = res.data;
        if (professionData.value.length > 0) {
            buildProfessionCascadeOptions();
        }
    } catch (error) {
        console.error("加载专业数据失败:", error);
    }
};


const getSecurity = async () => {
    try {
        const res = await tbwtAPI.getSecurity();
        securityData.value = res.data;
        if (securityData.value.length > 0) {
            buildSecurityCascadeOptions();
        }
    } catch (error) {
        console.error("加载责任单位数据失败:", error);
    }
};

const buildAreaTypeChildrenOptions = (firstLevelValue) => {
    switch (firstLevelValue) {
        case "控制中心":
        case "中间风井":
            return [];
        case "场段":
            return convertToCascadeOptions(allOptionsData.value["场段"] || [], "场段");
        case "主变电所":
            return convertToCascadeOptions(
                allOptionsData.value["主变电所"] || [],
                "主变电所"
            );
        case "车站":
            return convertToCascadeOptions(allOptionsData.value["站点"] || [], "站点");
        case "轨行区":
            return buildTrackAreaOptions();
        default:
            return [];
    }
};

const convertToCascadeOptions = (data, parentType) => {
    if (!data || data.length === 0) {
        return [];
    }
    if (Array.isArray(data)) {
        return data.map((item) => {
            let text, value;
            if (typeof item === "string") {
                text = item;
                value = item;
            } else if (typeof item === "object") {
                text = item.name || item.text || item.label || JSON.stringify(item);
                value = item.value || item.id || text;
            } else {
                text = String(item);
                value = String(item);
            }
            const disabled = text.includes("禁用");
            return {
                text,
                value,
                disabled,
            };
        });
    }
    if (typeof data === "object") {
        return Object.keys(data).map((key) => {
            const disabled = key.includes("禁用");
            return {
                text: key,
                value: key,
                disabled,
                children: Array.isArray(data[key])
                    ? convertToCascadeOptions(data[key], key)
                    : typeof data[key] === "object"
                        ? convertToCascadeOptions(
                            Object.keys(data[key]).map((k) => ({
                                name: k,
                                value: data[key][k],
                            })),
                            key
                        )
                        : undefined,
            };
        });
    }
    return [];
};

const buildTrackAreaOptions = () => {
    const directionOptions = allOptionsData.value["行车方向"] || [];
    return convertToCascadeOptions(directionOptions, "行车方向").map(
        (direction) => ({
            ...direction,
            children: buildTrackAreaThirdLevel(),
        })
    );
};

const buildTrackAreaThirdLevel = () => {
    const startStations = allOptionsData.value["站点"] || [];
    return convertToCascadeOptions(startStations, "站点").map((startStation) => ({
        ...startStation,
        children: buildTrackAreaFourthLevel(startStation.value),
    }));
};

const buildTrackAreaFourthLevel = () => {
    const endStations = allOptionsData.value["站点"] || [];
    return convertToCascadeOptions(endStations, "站点");
};
</script>

<style scoped>
:deep(.van-field.data-field) {
    margin-left: 1rem;
    width: calc(100vw - 2rem);
    border-radius: 10px;
    border: 1px solid #ccc;
    margin-bottom: 0.5rem;
}
</style>
